package com.example.forum.services.impl;

import com.example.forum.common.AppResult;
import com.example.forum.common.ResultCode;
import com.example.forum.dao.UserMapper;
import com.example.forum.exception.ApplicationException;
import com.example.forum.model.User;
import com.example.forum.services.IUserService;
import com.example.forum.uitls.MD5Util;
import com.example.forum.uitls.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

@Slf4j
@Service("IUserService")
public class UserServiceImpl implements IUserService {
    //注入UserMapping
    @Resource
    private UserMapper userMapping;

    @Override
    public void creatNormalUser(User user) {
        if (user == null || StringUtil.isEmpty(user.getUsername())
        || StringUtil.isEmpty(user.getNickname())
        ||StringUtil.isEmpty(user.getPassword())
        ||StringUtil.isEmpty(user.getSalt())) {
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        //判断用户是否存在，用用户名查询用户信息
        User existUser = userMapping.selectByUserName(user.getUsername());
        if (existUser != null){
            //打印日志
            log.info(ResultCode.FAILED_USER_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_EXISTS));
        }
        //如果不存在新增用户,设置用户信息插入数据库
        user.setGender((byte) 2);
        user.setArticleCount(0);
        user.setIsAdmin((byte) 0);
        user.setState((byte) 0);
        user.setDeleteState((byte) 0);
        // 当前日期
        Date date = new Date();
        user.setCreateTime(date);
        user.setUpdateTime(date);

        //写入数据库
        int row = userMapping.insertSelective(user);
        if (row != 1) {
            //打印日志
            log.info(ResultCode.FAILED_CREATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }
        //打印日志
        log.info("新增用户成功, username = " + user.getUsername() + ".");
    }

    @Override
    public User selectByUserName(String username) {
        if (StringUtil.isEmpty(username)){
            //打印日志
            log.info(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出错误
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        return userMapping.selectByUserName(username);
    }

    @Override
    public User login(String username, String password) {
        //非空校验
        if (StringUtil.isEmpty(username) || StringUtil.isEmpty(password)) {
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //参正确正确之后，判断密码是否一致
        //1.按照用户名查找用户信息
        User user = selectByUserName(username);
        //2.判断是否查出了结果，存在继续判断
        if (user == null) {
            //打印日志
            log.warn(ResultCode.FAILED_LOGIN.toString() + "username = " + username);
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }
        //3.对密码做校验
        String encryptPassword = MD5Util.md5Salt(password,user.getSalt());
        //4.判断是否相等
        if (!encryptPassword.equals(user.getPassword())){
            //打印日志
            log.warn(ResultCode.FAILED_LOGIN.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }
        //5.成功打印日志
        log.info("登陆成功 username = " + username );
        //6.登陆成功，返回用户信息
        return user;
    }

    @Override
    public User selectById(Long id) {
        //校验参数
        if (id == null) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //调用dao
        User user = userMapping.selectByPrimaryKey(id);
        //返回结果
        return user;
    }

    @Override
    public void modify(Long id,Byte gender, String nickname, String phonenum, String email, String remark) {
        if (id == null || (gender == null
                && StringUtil.isEmpty(nickname)
                && StringUtil.isEmpty(phonenum))
                && StringUtil.isEmpty(email)
                && StringUtil.isEmpty(remark)) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 校验用户状态
        User user = userMapping.selectByPrimaryKey(id);
        if (user == null || user.getDeleteState() == 1) {
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }

        // 构造一个修改对象
        User updateUser = new User();
        // 设置Id
        updateUser.setId(id);
        // 设置昵称
        if (!StringUtil.isEmpty(nickname)) {
            updateUser.setNickname(nickname);
        }
        // 设置电话
        if (!StringUtil.isEmpty(phonenum)) {
            updateUser.setPhoneNum(phonenum);
        }
        // 设置邮箱
        if (!StringUtil.isEmpty(email)) {
            updateUser.setEmail(email);
        }
        // 个人简介
        if (!StringUtil.isEmpty(remark)) {
            updateUser.setRemark(remark);
        }
        // 性别
        if (gender != null && gender >= 0 && gender <= 2) {
            updateUser.setGender(gender);
        }

        // 调用DAO
        int row = userMapping.updateByPrimaryKeySelective(updateUser);
        if (row != 1) {
            log.warn(ResultCode.FAILED_UPDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_UPDATE));
        }
    }
}
